package com.qd.admin.controller;

import cn.hutool.core.codec.Base64;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.cdqidi.dto.ApiResult;
import com.cdqidi.dto.ApiResultWrapper;
import com.google.code.kaptcha.Producer;
import com.qd.common.sys.constant.Constants;
import com.qd.system.config.AdminConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 *
 * @author sjk
 */
@RestController
@Slf4j
@RequiredArgsConstructor
public class CaptchaController {
    /**
     * math 计算验证码
     * char 字符串验证码
     */
    private static final String MATH_CAPTCHA_TYPE = "math";
    private static final String CHAR_CAPTCHA_TYPE = "char";
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;
    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    private final StringRedisTemplate stringRedisTemplate;
    private final AdminConfig adminConfig;

    /**
     * 生成验证码
     */
    @GetMapping(value = "/sys/captcha/captchaImage")
    public ApiResultWrapper<Object> getCode() {
        // 保存验证码信息
        final String uuid = IdWorker.get32UUID();
        final String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        String capStr;
        String code;
        BufferedImage image;
        String base64Image;
        // 生成验证码
        String captchaType = adminConfig.getCaptchaType();
        if (MATH_CAPTCHA_TYPE.equals(captchaType)) {
            final String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if (CHAR_CAPTCHA_TYPE.equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        } else {
            return ApiResult.error("验证码类型错误");
        }
        log.info("验证码: {}", code);
        stringRedisTemplate.opsForValue().set(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        try {
            try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()) {
                ImageIO.write(image, "jpg", os);
                base64Image = Base64.encode(os.toByteArray());
            }
        } catch (IOException e) {
            return ApiResult.error(e.getMessage());
        }

        final Map<String, Object> map = new HashMap<>(2);
        map.put("captchaId", uuid);
        map.put("img", base64Image);
        return ApiResult.success(map);
    }
}
